<template>
  <div class="showcanvas" ref="showCanvas">
    <div class="topshowbutton" v-if="showTitle && !isQianru">
      <div class="canvashead boadinfohead">
        <!-- <h1 class="boardtitle">{{ boardInfo.name }}</h1> -->
        <div class="gobackinfo" @click="goback">
          <i class="el-icon-arrow-left"></i>
          <span>{{ boardInfo.name }}</span>
        </div>
        <el-row :gutter="30">
          <el-col :span="8">
            <el-popover placement="top-start" title="公开分享链接" width="300" trigger="hover">
              <div>
                <el-form size="small" :inline="true">
                  <el-form-item>
                    <el-input ref="copytext" :value="shareUrl"></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="copyurl">复制</el-button>
                  </el-form-item>
                </el-form>
              </div>
              <el-button class="btntext" type="text" slot="reference">网址链接</el-button>
            </el-popover>
          </el-col>
          <el-col :span="8">
            <el-button @click="showEdit" v-if="boardInfo.powerType != 0">编辑</el-button>
          </el-col>
          <el-col :span="8">
            <i class="iconfont icon-quanping" @click="fullScreen"></i>
          </el-col>
        </el-row>
      </div>
    </div>
    <div :style="boardContentStyle">
      <div :style="backgroundStyle" :class="backageData.templateClass">
        <div v-for="(drage, index) in plugsData" :style="computedStyle(drage)" :class="{ 'defaultindex': defaultIndex }"
          :key="index" v-show="switchCardTab(drage)">
          <component :ref="'ref_' + drage.id" @showfile="showFileinfo" @submitBard="updateBardInfo"
            @setIndex="defaultIndex = !defaultIndex" :is="drage.type" :obj="drage" :isReload="true" :gotoUrl="gotoUrl"
            :getTableValue="getTableValue" @tabHideCardHandle="tabHideCardHandle" @dateSearchHandle="dateSearchHandle">
          </component>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import { getDetail } from '@/api/board'
// import { update } from '@/api/board'
// import { QueryLimitOne } from '@/api/dataLoad'
// import { query as statTableQuery } from '@/api/statistics'
import { zipe, unzipe } from '@/utils'
export default {
  name: "CanvasShow",
  props: {
    id: String,
    p: Number,
  },
  components: {
    // NewMap2: () => import("./type/NewMap2.vue"),
    // TableFile: () => import("./type/TableFile.vue"),
    SingleText: () => import("./type/SingleText.vue"),
    // CardTable: () => import("./type/CardTable.vue"),
    CardImg: () => import("./type/CardImg.vue"),
    // Time: () => import("./type/Time.vue"),
    // Card: () => import("./type/Card.vue"),
    // Rate: () => import("./type/Rate.vue"),
    // Pie: () => import("./type/Pie.vue"),
    // LiquidFill: () => import("./type/LiquidFill.vue"),
    // Progress: () => import("./type/Progress.vue"),
    // Gauge: () => import("./type/Gauge.vue"),
    // NewGauge: () => import("./type/NewGauge.vue"),
    // VideoPlay: () => import("./type/VideoPlay.vue"),
    // Embed: () => import("./type/Embed.vue"),
    // Submit: () => import("./type/Submit.vue"),
    // Status: () => import("./type/Status.vue"),
    // FileData: () => import("./type/File.vue"),
    // LineBarMixin: () => import("./type/LineBarMixin.vue"),
    // StatusGroup: () => import("./type/StatusGroup.vue"),
    // Camera: () => import("./type/Camera.vue"),
    // TimeOut: () => import("./type/TimeOut.vue"),
    // TimeSpeed: () => import("./type/TimeSpeed.vue"),
    // EchartMap: () => import("./type/EchartMap.vue"),
    // Scatter: () => import("./type/Scatter.vue"),
    // LineFigure: () => import("./type/LineFigure.vue"),
    // Figure: () => import("./type/Figure.vue"),
    // NewMap: () => import("./type/NewMap.vue"),
    TabSwitch: () => import("./type/TabSwitch.vue"),
    // DateSearch: () => import("./type/DateSearch.vue"),
    // Element: () => import("./type/Element.vue"),
    // Grid3D: () => import("./type/Grid3D.vue"),
    // Bar: () => import("./type/Bar.vue"),
    // Radar: () => import("./type/Radar.vue"),
    // Candlestick: () => import("./type/Candlestick.vue"),
    // Gantetu: () => import("./type/Gantetu.vue"),
    Context: () => import("./type/Context.vue"),
  },
  data() {
    return {
      isQianru: false,
      // 计算用的基础属性
      baseParam: {
        screenWidth: 0,
        screenHeight: 0,
      },
      // 背景样式
      backgroundStyle: {

      },
      boardInfo: {},
      // 动态参数
      backageData: {},
      plugsData: {},
      shareUrl: "",
      // 新的参数
      // wdiscount: 0,
      // hdiscount: 0,
      showTitle: false,
      timer: null,
      reloadTime: null,
      defaultIndex: false,
      videoVisible: false,
      imgVisible: false,
      proecjtUrl: "",
      // 数据缓存
      cardTableDataList: {},
      reloadDataTime: null,
      boardContentStyle: {},
      canvasStyle: {},
      hideCardIds: [],
    }
  },
  mounted() {
    var slef = this;
    window.onresize = function () {
      var screenHeight = document.body.clientHeight;
      if (screenHeight >= window.screen.height) {
        slef.showTitle = false;
      } else {
        slef.showTitle = true;
      }

      // // self.$nextTick(() => {
      //     console.log("重新调用")
      //     slef.getdetail();
      // // });

      slef.newsetbaseParam();
      slef.setBackageStyle();
    }
  },
  created() {
    if (this.$route.query.showtitle) {
      this.showTitle = true;
    }

    if (this.$route.query.isQianru) {
      this.isQianru = true;
    }
    this.shareUrl = window.location.origin + "/share/" + this.id

    this.getdetail();
  },
  watch: {
    '$route'(to, from) {
      //监听URL地址栏参数变化
      this.getdetail();
    }
  },
  beforeDestroy() {
    clearInterval(this.timer)
    clearInterval(this.reloadDataTime)
  },
  methods: {
    // 增加一个整个页面刷新
    setViewReload() {
      clearInterval(this.timer);

      var timeSize = 600;
      if (this.backageData.reloadTime) {
        timeSize = this.backageData.reloadTime;
      }

      this.timer = setInterval(() => {
        this.getdetail();
      }, timeSize * 1000);
    },
    showFileinfo({ type, url }) {
      if (type == 0) {
        this.imgVisible = true;
        this.proecjtUrl = url;
      } else if (type == 1) {
        this.videoVisible = true;
        this.proecjtUrl = url;
      }
    },
    copyurl() {
      this.$refs.copytext.select();
      document.execCommand("Copy") // 执行浏览器复制命令
      this.$message({
        message: '复制成功',
        type: 'success'
      })
    },
    goback() {
      this.$router.go(-1);
    },
    showEdit() {
      // const { href } = this.$router.resolve({ path: "/canvasediter", query: { id: this.boardInfo.id }, attrs: { target: '_blank' } })
      // window.open(href, '_blank')
      this.$router.push({ path: "/canvasediter", query: { id: this.boardInfo.id } })
    },
    // 全屏操作跳转到看板详情
    fullScreen() {
      // const { href } = this.$router.resolve({ path: "/canvas", query: { id: this.boardInfo.id }, attrs: { target: '_blank' } })
      // window.open(href, '_blank')
      var el = document.documentElement;
      var rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullscreen;
      if (typeof rfs != "undefined" && rfs) {
        rfs.call(el);
      };
      return;
    },
    getdetail() {
      const loading = this.$loading();

      // 解压缩数据
      var data = sessionStorage.getItem("jsonData");
     
      var jsonStr = unzipe(data);
      console.log(jsonStr);
      const jsonData = JSON.parse(jsonStr);
      
      if (jsonData) {
        this.backageData = jsonData.backageData;
        this.plugsData = jsonData.plugsData;

        this.newsetbaseParam();
        this.setBackageStyle();
        this.setViewReload();
      }

      loading.close();
      return false;

      getDetail({ id: this.id }).then((res) => {
        loading.close();
        if (res.data.code == 0 && res.data.data) {
          this.boardInfo = res.data.data;
          if (this.boardInfo.structure) {
            try {
              // 解压缩数据                            
              var jsonStr = unzipe(this.boardInfo.structure);
              const jsonData = JSON.parse(jsonStr);

              if (jsonData) {
                this.backageData = jsonData.backageData;
                this.plugsData = jsonData.plugsData;

                this.newsetbaseParam();
                this.setBackageStyle();
                this.setViewReload();
                // document.getElementsByTagName('title')[0].innerHTML = this.boardInfo.name;

                // 数据缓存请求方案
                this.runCardDataReload();
              }
            } catch (e) {
              this.$message.error("看板数据解析失败");
            }
          }
        } else {
          this.$message.error("获取看板详情失败");
        }
      }).catch(() => {
        loading.close();
      });
    },
    computedStyle(drage) {
      return {
        display: "flex",
        position: "absolute",
        zIndex: drage.style.zIndex,
        justifyContent: drage.style.justifyContent,
        alignItems: drage.style.alignItems,
        top: drage.style.top + "px",
        left: drage.style.left + "px",
        width: drage.style.width + "px",
        height: drage.style.height + "px",
      };
    },
    // 根据背景参数设置背景样式
    setBackageStyle() {
      var backgroundColor = "";
      var backgroundImage = "";

      // #region 看板编辑外层容器样式设置
      var canvasWidth = this.backageData.width;
      var canvasHeight = this.backageData.height;

      let scaleXValue = 1;
      let scaleYValue = 1;
      let scaleOrigin = "top left";
      let wrapWidth = this.baseParam.screenWidth;
      let wrapHeight = this.baseParam.screenHeight;

      // alert(wrapHeight)
      // // 等比例缩放画布验证
      if (wrapWidth < canvasWidth || wrapHeight < canvasHeight) {
        scaleXValue = Math.floor(wrapWidth / canvasWidth * 10000) / 10000;
        scaleYValue = Math.floor(wrapHeight / canvasHeight * 10000) / 10000;
        // 判断高是否溢出
        // if (wrapHeight < canvasHeight * scaleYValue) {
        if (canvasHeight > canvasWidth) {
          scaleYValue = Math.floor(wrapHeight / canvasHeight * 10000) / 10000;
          scaleXValue = scaleYValue;
          scaleOrigin = "top center";
        }
      }
      // #endregion

      if (this.backageData.backgroundImage.length) {
        backgroundImage = `url(${this.backageData.backgroundImage}`;
      } else if (this.backageData.backgroundColor.length > 0) {
        backgroundColor = this.backageData.backgroundColor;
      } else {
        backgroundColor = "#04142b";
      }

      this.backgroundStyle = {
        margin: "0 auto",
        position: "relative",
        backgroundImage,
        backgroundSize: "100% 100%",
        backgroundColor,
        backgroundColor,
        width: this.backageData.width + "px",
        height: this.backageData.height + "px",
        overflow: 'hidden',
        transform: `scale(${scaleXValue}, ${scaleYValue})`,
        transformOrigin: scaleOrigin,
      }
    },
    // 新的比例计算规则
    newsetbaseParam() {
      var screenWidth = document.body.clientWidth;
      if (this.showTitle && !this.isQianru) {
        var screenHeight = document.body.clientHeight - 70;
      } else {
        var screenHeight = document.body.clientHeight;
      }

      // this.wdiscount = (screenWidth / this.backageData.width * 100) / 100;
      // this.hdiscount = (screenHeight / this.backageData.height * 100) / 100;

      this.baseParam = {
        screenWidth,
        screenHeight
      }

      // console.log(this.baseParam);

      this.boardContentStyle = {
        width: screenWidth + "px",
        height: screenHeight + "px",
        // transform: 'translateX(-50%)',
      }
    },
    // 保存更新看板某些组件信息
    updateBardInfo() {
      var data = { "plugsData": this.plugsData, "backageData": this.backageData };
      var formData = {
        id: this.boardInfo.id,
        name: this.boardInfo.name,
        url: this.boardInfo.url,
        structure: JSON.stringify(data)
      }
      update(formData).then((res) => {
        if (res.data.code == 0) {
          this.$message({
            message: "保存成功",
            type: "success",
          });

        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    gotoUrl(obj) {
      if (obj.contactType > 0) {
        if (obj.contactType == 1 && obj.boardId) {
          this.$router.replace({ path: `/share/${obj.boardId}` })
          // this.$router.replace({ path: "/canvas", query: { id: this.obj.boardId } })
        }
        if (obj.contactType == 2 && obj.url) {
          this.$router.replace(obj.url);
        }
      }
    },

    // #region 模拟数据请求和缓存
    // 获取组件内全部的请求统计循环调用api
    runCardDataReload() {
      var cardTableDataList = {};
      clearInterval(this.reloadDataTime);
      var tableIds = [];

      if (this.plugsData.length) {
        // 循环看板组件
        this.plugsData.forEach(e => {
          // 筛选出组件类型
          if (["Gauge", "Rate", "Card", "Status", "LiquidFill", "Progress"].indexOf(e.type) >= 0) {
            // 判断是否绑定表格
            if (e.tableData.tableId) {
              // 已存在表格做合并
              if (cardTableDataList[e.tableData.tableId]) {
                // 判断请求时间是否最小
                var current = cardTableDataList[e.tableData.tableId];

                // 请求api倒计时用最小值
                if (current.timeSpeed > e.tableData.reloadTime) {
                  current.timeSpeed = e.tableData.reloadTime;
                  if (e.tableData.reloadTime < 2) {
                    current.timeSpeed = 2;
                  }
                }
                // 最大筛选时间范围
                // if (current.filterTimeType < e.tableData.filterTimeType) {
                //     current.filterTimeType = e.tableData.filterTimeType;
                // }
              } else {
                var data = {
                  timeSpeed: (e.tableData.reloadTime ? e.tableData.reloadTime : 60) * 1,
                  itemdata: [],
                  listdata: [],
                  type: e.tableData.type,
                  filterTimeType: (e.tableData.filterTimeType ? e.tableData.filterTimeType : 15) * 1,
                };
                cardTableDataList[e.tableData.tableId] = data;
                tableIds.push(e.tableData.tableId);
              }
            }
          }
        })
      }

      this.cardTableDataList = cardTableDataList;

      var self = this;
      var timeRecord = 0;
      if (tableIds.length) {
        this.reloadDataTime = setInterval(function () {
          tableIds.forEach((tableId, i) => {
            var table = cardTableDataList[tableId];
            // console.log(table.timeSpeed)
            if (timeRecord == 0 || (timeRecord % table.timeSpeed) == 0) {
              self.getTableData(tableId, table.type, table.filterTimeType);
            }
          });
          timeRecord++;
        }, 1000);
      }
    },
    getTableData(tableId, type, filterTimeType) {
      var listQuery = {
        pageInfo: {
          pageSize: 1,
          page: 1,
          totalCount: 0
        },
        id: tableId,
        orderBy: undefined,
        orderAsc: undefined,
        name: undefined,
        typeInc: [],
        startTime: undefined,
        beginTime: undefined,
        endTime: undefined,
        exportStartTime: undefined,
      };

      const end = new Date();
      const start = new Date();
      if (type == 0) {
        listQuery.isOnlie = true;

        // 查询一天内数据
        start.setTime(start.getTime() - 3600 * 1000 * 24);
        listQuery.beginTime = this.parseTime(start);
        listQuery.endTime = this.parseTime(end);
      } else {
        listQuery.isOnlie = false;

        start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
        listQuery.beginTime = this.parseTime(start, "{y}-{m}-{d}");
        listQuery.endTime = this.parseTime(end);
      }

      if (type == 1) {
        statTableQuery(listQuery)
          .then((response) => {
            if (response.data.code == 0) {
              if (response.data.data.dataResult) {
                var itemdata = response.data.data.dataResult.columns;
                var listdata = response.data.data.dataResult.dataList;

                this.cardTableDataList[tableId].itemdata = itemdata;
                this.cardTableDataList[tableId].listdata = listdata;
              }
            }
          })
      } else {
        QueryLimitOne(listQuery).then((response) => {
          if (response.data.code == 0) {
            if (response.data.data.dataResult) {
              var itemdata = response.data.data.dataResult.columns;
              var listdata = response.data.data.dataResult.dataList;

              this.cardTableDataList[tableId].itemdata = itemdata;
              this.cardTableDataList[tableId].listdata = listdata;
            }
          }
        })
      }
    },
    getTableValue(tableId, lineId, length) {
      if (this.cardTableDataList[tableId]) {
        var tableData = this.cardTableDataList[tableId];
        if (tableData && tableData.itemdata.length && tableData.listdata.length) {

          var itemIndex = -1;
          tableData.itemdata.forEach((e, i) => {
            if (e.id === lineId) {
              itemIndex = i;
            }
          })

          if (itemIndex >= 0) {
            return { code: 200, data: tableData.listdata[0][itemIndex] };
          }
        }
        return { code: 404, data: 0 };
      }
    },
    // #endregion

    // tab组件 动态隐藏组件内容
    tabHideCardHandle(hideids, showid) {
      var arr = this.hideCardIds.concat(hideids);
      showid.forEach(id => {
        if (arr.indexOf(id + "") != -1) {
          arr.splice(arr.indexOf(id + ""), 1);
        }
      })

      this.hideCardIds = [...new Set(arr)];
    },
    switchCardTab(drage) {
      if (this.hideCardIds.indexOf(drage.id + "") != -1) {
        return false;
      }
      return true;
    },
    // 时间筛选触主组件方法
    dateSearchHandle(beginTime, endTime, ids) {
      ids.forEach(e => {
        // 调用绑定组件刷新数据
        this.$refs['ref_' + e][0].dateSearch(beginTime, endTime);
      })
    },
  }
}
</script>

<style src="@/styles/canvasedit.css"></style>
<style scoped>
.showcanvas::-webkit-scrollbar {
  display: none;
}

.showcanvas {
  background-color: #313239;
  width: 100%;
  height: 100%;
  align-items: center;
  justify-content: center;
  overflow-y: auto;
}

.btntext {
  color: #666666;
  text-decoration: underline;
}

.defaultindex {
  position: relative !important;
  z-index: 0 !important;
}
</style>